<template>
  <view class="dashboard-container">
    <!-- 顶部信息 -->
    <view class="header">
      <text class="header-time">{{ currentTime }}</text>
      <text class="header-title">起重机智能安全保障平台</text>
      <view class="header-admin-wrapper" @tap="toggleAdminMenu">
        <text class="header-admin">管理员</text>
        <view class="admin-dropdown" v-show="showAdminMenu">
          <view class="dropdown-item" @tap.stop="goToStorageTest">
            <text class="dropdown-icon">🔧</text>
            <text class="dropdown-text">存储测试</text>
          </view>
          <view class="dropdown-item" @tap.stop="logout">
            <text class="dropdown-icon">🚪</text>
            <text class="dropdown-text">退出登录</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 页面标题 -->
    <view class="page-title">起重机智能安全保障平台</view>

    <!-- 功能菜单网格 -->
    <view class="menu-grid">
      <view
        class="menu-item menu-item-running"
        data-type="data"
        @tap="navigateTo('runningData')"
      >
        <text class="menu-item-icon">📊</text>
        <text class="menu-item-text">运行数据</text>
      </view>
      <view
        class="menu-item menu-item-status"
        data-type="status"
        @tap="navigateTo('statusData')"
      >
        <text class="menu-item-icon">🎨</text>
        <text class="menu-item-text">状态数据</text>
      </view>
      <view
        class="menu-item menu-item-maintenance"
        data-type="maintenance"
        @tap="navigateTo('maintenance')"
      >
        <text class="menu-item-icon">⚙️</text>
        <text class="menu-item-text">基础运维</text>
      </view>
      <view
        class="menu-item menu-item-message"
        data-type="alerts"
        @tap="navigateTo('messageCenter')"
      >
        <text class="menu-item-icon">🔔</text>
        <text class="menu-item-text">消息中心</text>
      </view>
      <view
        class="menu-item menu-item-report"
        data-type="reports"
        @tap="navigateTo('reportCenter')"
      >
        <text class="menu-item-icon">📋</text>
        <text class="menu-item-text">报表中心</text>
      </view>
      <view
        class="menu-item menu-item-system"
        data-type="system"
        @tap="navigateTo('systemManage')"
      >
        <text class="menu-item-icon">⚙️</text>
        <text class="menu-item-text">生产调度</text>
      </view>
    </view>

    <!-- 内容详情区域 -->
    <view class="content-section" style="height: 50vh">
      <view class="section-title">内容详情</view>
      <text class="welcome-text"
        >欢迎使用起重机智能安全保障平台。在此区域可以查看各类详细信息，如设备运行报告、维护记录等。</text
      >
    </view>
  </view>
</template>

<script>
import { getDashboardData } from "@/api/biz/crane";
import { checkStorageStatus } from "@/utils/auth";

export default {
  data() {
    return {
      currentTime: "",
      showAdminMenu: false,
      dashboardData: {
        deviceStatusSummary: {
          totalCrane: 12,
          normalRunning: 10,
          maintenanceStatus: 2,
          routineChecks: 3,
          safetyIssues: 0,
        },
        latestAlerts: [],
        maintenancePlans: [],
      },
    };
  },
  onLoad() {
    this.updateTime();
    setInterval(this.updateTime, 60000); // 每分钟更新一次时间
    this.loadDashboardData();
    // 添加点击外部关闭下拉菜单的事件监听
    this.addClickOutsideListener();

    // 调试：检查存储状态
    console.log("首页加载，存储状态检查:");
    checkStorageStatus();
  },
  onUnload() {
    // 移除事件监听 - 添加this存在性检查以避免错误
    if (this && this.removeClickOutsideListener) {
      this.removeClickOutsideListener();
    }
  },
  methods: {
    updateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    },
    loadDashboardData() {
      // 实际项目中应该调用API获取数据
      // 这里使用模拟数据
      const data = getDashboardData();
      this.dashboardData = data;
    },
    navigateTo(module) {
      // 根据不同模块跳转到相应页面
      console.log("跳转到模块：", module);
      // 这里仅做示例，实际应该根据项目需求进行页面跳转
    },
    toggleAdminMenu() {
      this.showAdminMenu = !this.showAdminMenu;
    },
    goToStorageTest() {
      this.showAdminMenu = false;
      uni.navigateTo({
        url: "/pages/test/storage",
      });
    },
    async logout() {
      try {
        // 调用后台退出接口
        await this.$store.dispatch("LogOut");
        // 跳转到登录页
        uni.reLaunch({ url: "/pages/login" });
      } catch (error) {
        console.error("退出登录失败:", error);
        // 即使接口调用失败，也清理本地token并跳转登录页
        this.$store.dispatch("LogOut").catch(() => {});
        uni.reLaunch({ url: "/pages/login" });
      }
    },
    addClickOutsideListener() {
      // 监听点击事件，用于关闭下拉菜单
      this._clickOutsideHandler = (e) => {
        if (this.showAdminMenu) {
          // 检查点击是否在下拉菜单外部
          const adminWrapper = this.$el.querySelector(".header-admin-wrapper");
          if (adminWrapper && !adminWrapper.contains(e.target)) {
            this.showAdminMenu = false;
          }
        }
      };
      // 添加document存在性检查以避免错误
      if (typeof document !== "undefined") {
        document.addEventListener("click", this._clickOutsideHandler);
      }
    },
    removeClickOutsideListener() {
      // 添加document存在性检查以避免错误
      if (this._clickOutsideHandler && typeof document !== "undefined") {
        document.removeEventListener("click", this._clickOutsideHandler);
        this._clickOutsideHandler = null;
      }
    },
  },
};
</script>

<style scoped>
/* 引入自定义样式 */
@import "../static/scss/dashboard.scss";
</style>
